<?php
//related_word_mining_easy 相关词挖掘简易版
header('Content-Type:text/html;charset=utf8');
include_once "../db_orm.php";
include_once "../function.php";

use Illuminate\Database\Capsule\Manager as DB;

$db_table1 = 'product';
$db_table2 = 'related_word_mining_easy';

//查询相关词表没顶级关键词的product记录
$res = DB::table($db_table1)
    ->leftJoin($db_table2, function ($join) use ($db_table1, $db_table2) {
        $join->on($db_table1 . '.name', '=', $db_table2 . '.keyword')
            ->where($db_table2 . '.p_id', '=', 0);
    })->select($db_table1 . '.id', $db_table1 . '.name', $db_table2 . '.p_id')
    ->where($db_table2 . '.p_id', '=', null)
    ->orderBy('id')->get();
//var_dump($res);
//exit;

$host = "http://apis.5118.com";
$path = "/keyword/easy/related";
$apikey = "45084F1900C34991A57C7E880BA683FE";
$headers = array();
array_push($headers, "Authorization:" . $apikey);
//根据API的要求，定义相对应的Content-Type
array_push($headers, "Content-Type" . ":" . "application/x-www-form-urlencoded; charset=UTF-8");
$url = $host . $path;

if (!empty($res)) {
    foreach ($res as $key => $value) {
        $bodys = "keyword=" . $value['name'];
        $bodyInfo = curl_post($url, $headers, $bodys);
        $bodyInfo = json_decode($bodyInfo, true);

        if (!empty($bodyInfo)) {
            if ($bodyInfo['errcode'] == 0) {
                //写入数据库
                $last_id = DB::table($db_table2)->insertGetId(['keyword' => $value['name'], 'p_id' => 0]);
                if (!empty($bodyInfo['data'])) {
                    $data = array();
                    foreach ($bodyInfo['data'] as $v) {
                        $data[] = array('keyword' => $v, 'p_id' => $last_id);
                    }
                    DB::table($db_table2)->insert($data);
                }
            } else {
                echo $bodyInfo['errmsg'] . "\n";
//                exit();
            }
        }
        echo ($key + 1) . "/" . count($res) . "\n";
        usleep(900000);
    }
}
echo 'succ';

//function curl_post($url, $headers, $bodys)
//{
//    $curl = curl_init();
//    curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'POST');
//    curl_setopt($curl, CURLOPT_URL, $url);
//    curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
//    curl_setopt($curl, CURLOPT_FAILONERROR, false);
//    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
//    curl_setopt($curl, CURLOPT_HEADER, true);
//    if (1 == strpos("$" . $url, "https://")) {
//        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
//        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
//    }
//    curl_setopt($curl, CURLOPT_POSTFIELDS, $bodys);
//    $result = curl_exec($curl);
////    $bodyInfo = '';
//    if (curl_getinfo($curl, CURLINFO_HTTP_CODE) == '200') {
//        $headerSize = curl_getinfo($curl, CURLINFO_HEADER_SIZE); //获取header长度
//        $bodyInfo = substr($result, $headerSize); //截取掉header
//    }
//    curl_close($curl);
//    return $bodyInfo;
//}

